import { useState, useEffect } from 'react';
import {
  Box,
  Grid,
  Card,
  CardContent,
  CardMedia,
  Typography,
  IconButton,
  Pagination,
  TextField,
  InputAdornment,
  CircularProgress,
  Alert,
  Chip,
} from '@mui/material';
import { Search as SearchIcon, Delete as DeleteIcon } from '@mui/icons-material';
import { ResourceService, Resource } from '../services/ResourceService';
import { useAuth } from '../../auth/AuthContext';
import { useNavigate } from 'react-router-dom';

const formatSize = (bytes: number): string => {
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  if (bytes === 0) return '0 B';
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
};

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString('zh-CN');
};

const ResourceList = () => {
  const [resources, setResources] = useState<Resource[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(9);
  const [searchQuery, setSearchQuery] = useState('');
  const [searching, setSearching] = useState(false);
  
  const { user } = useAuth();
  const navigate = useNavigate();

  const fetchResources = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await ResourceService.getResourceList(page, pageSize);
      setResources(response.records);
      setTotalPages(Math.ceil(response.total / pageSize));
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取资源列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    if (!searchQuery.trim()) {
      fetchResources();
      return;
    }

    try {
      setSearching(true);
      setError(null);
      const response = await ResourceService.queryResources(searchQuery);
      setResources(response.records);
      setTotalPages(Math.ceil(response.total / pageSize));
    } catch (err) {
      setError(err instanceof Error ? err.message : '搜索资源失败');
    } finally {
      setSearching(false);
    }
  };

  useEffect(() => {
    if (!searching) {
      console.log('调用fetchResources获取资源列表');
      fetchResources();
    }
  }, [page, pageSize]); // 添加pageSize作为依赖，确保组件首次加载时调用

  const handleDelete = async (id: string) => {
    if (!window.confirm('确定要删除这个资源吗？')) return;
    
    try {
      await ResourceService.deleteResource(id);
      fetchResources();
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除失败');
    }
  };

  const handleResourceClick = (resourceId: string) => {
    navigate(`/resources/${resourceId}`);
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" p={3}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ mb: 3 }}>
        <TextField
          fullWidth
          variant="outlined"
          placeholder="搜索资源..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={handleSearch} disabled={searching}>
                  {searching ? <CircularProgress size={24} /> : <SearchIcon />}
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        {resources.map((resource) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={resource.id}>
            <Card 
              sx={{ 
                height: '100%', 
                display: 'flex', 
                flexDirection: 'column',
                cursor: 'pointer',
                '&:hover': {
                  boxShadow: 6,
                  transform: 'translateY(-4px)',
                  transition: 'transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out'
                }
              }}
              onClick={() => handleResourceClick(resource.id)}
            >
              <CardMedia
                component="img"
                height="250"
                image={resource.coverImageUrl || resource.coverUrl || '/covers/newuser.png'}
                alt={resource.title}
                onError={(e) => {
                  // 图片加载失败时使用本地默认图片
                  const target = e.target as HTMLImageElement;
                  target.onerror = null; // 防止无限循环
                  target.src = '/covers/newuser.png';
                }}
              />
              <CardContent sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
                <Typography gutterBottom variant="h6" component="div" noWrap>
                  {resource.title}
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 1, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                  {resource.description}
                </Typography>
                
                <Box sx={{ mt: 'auto' }}>
                  <Typography variant="body2" color="text.secondary">
                    大小：{formatSize(resource.size)}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    上传者：{resource.uploaderName}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    上传时间：{formatDate(resource.uploadTime)}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    下载次数：{resource.downloadCount || 0}
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    所需积分：{resource.points !== undefined ? resource.points : 0}
                  </Typography>
                  
                  {resource.tags && resource.tags.length > 0 && (
                    <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                      {resource.tags.map((tag, index) => (
                        <Chip 
                          key={index} 
                          label={tag} 
                          size="small" 
                          sx={{ fontSize: '0.7rem' }}
                        />
                      ))}
                    </Box>
                  )}
                </Box>
                
                {user && (user.id === resource.uploaderId || user.role === 'admin') && (
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 1 }}>
                    <IconButton
                      onClick={(e) => {
                        e.stopPropagation(); // 阻止事件冒泡
                        handleDelete(resource.id);
                      }}
                      size="small"
                      color="error"
                      title="删除"
                    >
                      <DeleteIcon />
                    </IconButton>
                  </Box>
                )}
              </CardContent>
            </Card>
          </Grid>
        ))}
        {resources.length === 0 && (
          <Grid item xs={12}>
            <Typography variant="body1" color="text.secondary" align="center">
              暂无资源
            </Typography>
          </Grid>
        )}
      </Grid>

      {!searching && totalPages > 1 && (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <Pagination
            count={totalPages}
            page={page}
            onChange={(_, value) => setPage(value)}
            color="primary"
          />
        </Box>
      )}
    </Box>
  );
};

export default ResourceList;